package com.yunatt.uitls;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

public class ImageDuplicateChecker {

    public static void main(String[] args) {
        String imagePath1 = "559cd713-6223-485e-aa99-301e02f42fa9.jpg";
        String imagePath2 = "3c3cf8dc-d86e-45a5-88b1-4b8f38023f2f.jpg";

        try {
            String hash1 = calculateAverageHash(imagePath1);
            String hash2 = calculateAverageHash(imagePath2);
            System.out.println(hash1.length());
            System.out.println(hash2);
            double similarity = compareImageHashes(hash1, hash2);

            if (similarity > 0.95) {
                System.out.println("The images are duplicate.");
            } else {
                System.out.println("The images are not duplicate.");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static String calculateAverageHash(String imagePath) throws IOException {
        imagePath="C:\\dynamicface\\picture\\"+imagePath;
        BufferedImage image = ImageIO.read(new File(imagePath));
        image = resize(image, 8, 8); // Resize the image to 8x8

        int sum = 0;
        for (int y = 0; y < image.getHeight(); y++) {
            for (int x = 0; x < image.getWidth(); x++) {
                sum += image.getRGB(x, y) & 0xFF;
            }
        }

        int avg = sum / 64; // Average pixel value
        StringBuilder hash = new StringBuilder();
        for (int y = 0; y < image.getHeight(); y++) {
            for (int x = 0; x < image.getWidth(); x++) {
                hash.append((image.getRGB(x, y) & 0xFF) > avg ? '1' : '0');
            }
        }

        return hash.toString();
    }

    public static double compareImageHashes(String hash1, String hash2) {
        if (hash1.length() != hash2.length()) {
            return 0.0;
        }

        int difference = 0;
        for (int i = 0; i < hash1.length(); i++) {
            if (hash1.charAt(i) != hash2.charAt(i)) {
                difference++;
            }
        }

        return 1.0 - (double) difference / hash1.length();
    }

    public static BufferedImage resize(BufferedImage image, int width, int height) {
        BufferedImage resizedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
        resizedImage.getGraphics().drawImage(image, 0, 0, width, height, null);
        return resizedImage;
    }
}